﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static LiWi.Shell;

namespace LiWiTools
{
    public partial class UserControlFirst : UserControl
    {
        int _inNum, _outNum;
        private Label[] labIN;
        private Button[] btnIN;
        private Button[] btnOUT;
        public bool drawIN, drawOUT, drawPWM, drawAD;
        Data IPName;
        public UserControlFirst(Data IP)
        {
            IPName = IP;
            InitializeComponent();
            tabControl1.SelectedIndexChanged += async (sender, e) =>
            {
                switch (tabControl1.SelectedIndex)
                {
                    case 0:
                        if (!drawIN)
                        {
                            await DrawIN(tabControl1.TabPages[0]);
                            //drawIN = true;
                        }
                        break;
                    case 1:
                        if (!drawOUT)
                        {
                            await DrawOUT(tabControl1.TabPages[1]);
                            //drawOUT = true;
                        }
                        break;
                    case 2:
                        if (!drawPWM)
                        {
                            await DrawPWM(tabControl1.TabPages[2]);
                            drawPWM = true;
                        }
                        break;
                    case 3:
                        if (!drawAD)
                        {
                            await DrawADAndDA(tabControl1.TabPages[3]);
                            drawAD = true;
                        }
                        break;
                }

            };


        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
        }


        /// <summary>
        /// 定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {

            if (IPName.handle != IntPtr.Zero)
            {
                uint value = 0;
                //刷新in窗口
                if (tabControl1.SelectedIndex == 0)
                {
                    for (int i = 0; i < _inNum; i++)
                    {
                        PMC_GetIn(IPName.handle, i, ref value);
                        if (value == 1)
                        {
                            labIN[i].BackColor = Color.Green;
                        }
                        else labIN[i].BackColor = Color.White;

                        //反转                      
                        PMC_GetInvertIn(IPName.handle, i, ref ToolsForm.dataControl[IPName].inRev[i]);
                        if (ToolsForm.dataControl[IPName].inRev[i] == 1)
                        {
                            btnIN[i].BackColor = Color.Green;
                        }
                        else btnIN[i].BackColor = Color.White;
                    }

                }
                //刷新out数据
                else if (tabControl1.SelectedIndex == 1)
                {
                    for (int i = 0; i < _outNum; i++)
                    {
                        PMC_GetOp(IPName.handle, i, ref ToolsForm.dataControl[IPName].outStata[i]);
                        if (ToolsForm.dataControl[IPName].outStata[i] == 1)
                        {
                            btnOUT[i].BackColor = Color.Green;
                        }
                        else
                        {
                            btnOUT[i].BackColor = Color.White;
                        }
                    }
                }
                //刷新AD/DA数据
                //else if(tabControl1.SelectedIndex==3)
                if (tabControl1.SelectedIndex == 3)
                {
                    float value1 = 0;
                    for (int i = 0; i < ToolsForm.dataControl[IPName].ADNum; i++)
                    {
                        PMC_GetAD(IPName.handle, i, ref value1);
                        Control adread = tabControl1.TabPages[3].Controls.Find($"ADRead{i}", true).FirstOrDefault();
                        if (adread != null && adread is Label)
                        {
                            adread.Text = value1.ToString("F2");
                        }
                    }
                    for (int i = 0; i < ToolsForm.dataControl[IPName].DANum; i++)
                    {
                        PMC_GetDA(IPName.handle, i, ref value1);
                        Control daread = tabControl1.TabPages[3].Controls.Find($"DARead{i}", true).FirstOrDefault();
                        if (daread != null && daread is Label)
                        {
                            daread.Text = value1.ToString("F2");
                        }
                    }
                }
            }
        }


        public void DrawControl()
        {
            while (tabControl1.TabPages.Count > 0) tabControl1.TabPages.RemoveAt(0);
            string[] name = { "IN", "OUT", "PWM", "AD/DA" };
            foreach (var item in name)
            {
                TabPage tabPage = new TabPage(item);
                tabControl1.TabPages.Add(tabPage);
            }
            tabControl1.SelectedIndex = 0;
            DrawIN(tabControl1.TabPages[0]);

        }

        /// <summary>
        /// 创建IN
        /// </summary>
        /// <returns></returns>
        public async Task DrawIN(TabPage num)
        {
            _inNum = ToolsForm.dataControl[IPName].INNum;
            labIN = new Label[_inNum];
            btnIN = new Button[_inNum];
            //初始化控件
            this.Invoke(new Action(() =>
            {
                // 设置Label的初始位置和大小  
                int Width = 70;
                int Height = 20;
                int Margin = 30;

                // 用于记录当前Label的Y坐标（垂直位置）  
                int currentY = Margin;

                // 用于记录当前行已经放置了多少个Label  
                int labelCountInRow = 0;

                // 创建一个最大列数的变量（根据窗口宽度动态调整）  
                int maxLabelsInRow = (this.ClientSize.Width - (2 * Margin)) / (Width + Margin);
                //IN
                for (int i = 0; i < _inNum; i++)
                {
                    // 创建Label控件  
                    labIN[i] = new Label();
                    labIN[i].Text = "IN " + i;
                    labIN[i].AutoSize = false; // 确保Label大小固定  
                    labIN[i].Size = new System.Drawing.Size(Width, Height);
                    labIN[i].TextAlign = ContentAlignment.MiddleCenter;

                    btnIN[i] = new Button();
                    btnIN[i].Text = "IN" + i+"反转";
                    btnIN[i].AutoSize = false; // 确保Label大小固定  
                    btnIN[i].Size = new System.Drawing.Size(Width, Height);
                    btnIN[i].TextAlign = ContentAlignment.MiddleCenter;
                    int value = i;
                    btnIN[i].Click += new EventHandler((sender, e) =>
                    {
                        if (ToolsForm.dataControl[IPName].inRev[value] == 0) PMC_SetInvertIn(IPName.handle, value, 1);
                        else PMC_SetInvertIn(IPName.handle, value, 0);
                    });

                    // 计算Label的X坐标（水平位置）  
                    int currentX = Margin + (Width + Margin) * labelCountInRow;

                    // 设置Label的位置  
                    labIN[i].Location = new System.Drawing.Point(currentX, currentY);
                    btnIN[i].Location = new System.Drawing.Point(currentX, currentY+20);
                    // 将Label添加到表单的控件集合中  
                    num.Controls.Add(labIN[i]);
                    num.Controls.Add(btnIN[i]);

                    // 更新当前行Label的数量  
                    labelCountInRow++;

                    // 如果当前行已经放置了足够的Label，则移动到下一行  
                    if (labelCountInRow >= maxLabelsInRow)
                    {
                        currentY += Height + Margin;
                        labelCountInRow = 0;
                    }
                }
            }));
        }

        /// <summary>
        /// 创建OUT
        /// </summary>
        /// <returns></returns>
        public async Task DrawOUT(TabPage num)
        {
            _outNum = ToolsForm.dataControl[IPName].OUTNum;
            btnOUT = new Button[_outNum];
            //初始化控件
            this.Invoke(new Action(() =>
            {
                // 设置Label的初始位置和大小  
                int Width = 80;
                int Height = 30;
                int Margin = 30;

                // 用于记录当前Label的Y坐标（垂直位置）  
                int currentY = Margin;

                // 用于记录当前行已经放置了多少个Label  
                int labelCountInRow = 0;

                // 创建一个最大列数的变量（根据窗口宽度动态调整）  
                int maxLabelsInRow = (this.ClientSize.Width - (2 * Margin)) / (Width + Margin);
                //OUT

                int buttonCountInRow = 0;
                int maxButtonsInRow = (this.ClientSize.Width - (2 * Margin)) / (Width + Margin);
                for (int i = 0; i < _outNum; i++)
                {
                    // 创建Button控件  
                    btnOUT[i] = new Button();
                    btnOUT[i].Text = "OUT " + i;
                    btnOUT[i].Size = new System.Drawing.Size(Width, Height);

                    // 为Button添加点击事件（可选）
                    int value = i;
                    btnOUT[i].Click += new EventHandler((sender, e) =>
                    {
                        if (ToolsForm.dataControl[IPName].outStata[value] == 0) PMC_SetOp(IPName.handle, value, 1);
                        else PMC_SetOp(IPName.handle, value, 0);
                    });

                    // 计算Button的X坐标（水平位置）  
                    int currentX = Margin + (Width + Margin) * buttonCountInRow;

                    // 设置Button的位置  
                    btnOUT[i].Location = new System.Drawing.Point(currentX, currentY);

                    // 将Button添加到表单的控件集合中  
                    num.Controls.Add(btnOUT[i]);

                    // 更新当前行Button的数量  
                    buttonCountInRow++;

                    // 如果当前行已经放置了足够的Button，则移动到下一行  
                    if (buttonCountInRow >= maxButtonsInRow)
                    {
                        currentY += Height + Margin;
                        buttonCountInRow = 0;
                    }
                }
            }));
        }

        /// <summary>
        /// 绘制PWM
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public async Task DrawPWM(TabPage num)
        {
            // 设置Label的初始位置和大小  
            int Width = 50;
            int Height = 40;
            int Margin = 100;
            int xOffset = Margin, yOffset = Margin;
            Label nameNum = new Label { Text = "PWM编号", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            xOffset += Margin;
            Label zhankong = new Label { Text = "占空比", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            xOffset += Margin;
            Label pinlv = new Label { Text = "频率", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            num.Controls.Add(nameNum);
            num.Controls.Add(zhankong);
            num.Controls.Add(pinlv);

            xOffset = Margin;
            yOffset += Margin / 2;
            Label PWM0 = new Label { Text = "PWM0", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            xOffset += Margin;
            NumericUpDown zhankong0 = new NumericUpDown { DecimalPlaces = 2, Value = (decimal)0.000, Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            xOffset += Margin;
            NumericUpDown pinlv0 = new NumericUpDown { DecimalPlaces = 2, Maximum = 100000, Value = (decimal)1000, Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            num.Controls.Add(PWM0);
            num.Controls.Add(zhankong0);
            num.Controls.Add(pinlv0);

            xOffset = Margin;
            yOffset += Margin / 2;
            Label PWM1 = new Label { Text = "PWM1", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            xOffset += Margin;
            NumericUpDown zhankong1 = new NumericUpDown { DecimalPlaces = 2, Value = (decimal)0.000, Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            xOffset += Margin;
            NumericUpDown pinlv1 = new NumericUpDown { DecimalPlaces = 2, Maximum = 100000, Value = (decimal)1000, Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            num.Controls.Add(PWM1);
            num.Controls.Add(zhankong1);
            num.Controls.Add(pinlv1);

            yOffset += Margin / 2;
            xOffset = 2 * Margin;
            Button btnread = new Button { Text = "浏览", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            btnread.Click += (sender, e) =>
            {
                float value = 0;
                PMC_GetPwmDuty(IPName.handle, 0, ref value);
                zhankong0.Value = (decimal)value;
                PMC_GetPwmDuty(IPName.handle, 1, ref value);
                zhankong1.Value = (decimal)value;
                PMC_GetPwmFreq(IPName.handle, 0, ref value);
                pinlv0.Value = (decimal)value;
                PMC_GetPwmFreq(IPName.handle, 1, ref value);
                pinlv1.Value = (decimal)value;
            };
            xOffset += Margin;
            Button btnwrite = new Button { Text = "修改", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
            btnwrite.Click += (sender, e) =>
            {
                PMC_SetPwmDuty(IPName.handle, 0, (float)zhankong0.Value);
                PMC_SetPwmDuty(IPName.handle, 1, (float)zhankong1.Value);
                PMC_SetPwmFreq(IPName.handle, 0, (float)pinlv0.Value);
                PMC_SetPwmFreq(IPName.handle, 1, (float)pinlv1.Value);
                MessageBox.Show("修改成功");
            };
            num.Controls.Add(btnread);
            num.Controls.Add(btnwrite);
        }

        /// <summary>
        /// 绘制AD/DA
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public async Task DrawADAndDA(TabPage num)
        {


            // 设置Label的初始位置和大小  
            int Width = 60;
            int Height = 20;
            int Margin = 60;
            int xOffset = 3 * Margin, yOffset = Margin;
            //AD控件
            Label labelad = new Label { TextAlign = ContentAlignment.MiddleCenter, Text = $"读取值：", Size = new Size(Width, Height), Location = new Point(Convert.ToInt16(xOffset - 1.5 * Margin), yOffset + Margin / 2) };
            num.Controls.Add(labelad);
            for (int i = 0; i < ToolsForm.dataControl[IPName].ADNum; i++)
            {
                Label adName = new Label { TextAlign = ContentAlignment.MiddleCenter, Text = $"AD{i}", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
                Label adNum = new Label { Name = $"ADRead{i}", TextAlign = ContentAlignment.MiddleCenter, Text = "0.00", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset + Margin / 2) };
                xOffset += Margin;
                num.Controls.Add(adName);
                num.Controls.Add(adNum);
            }
            //DA控件
            yOffset += 2 * Margin;
            xOffset = 3 * Margin;
            Label labelda = new Label { TextAlign = ContentAlignment.MiddleCenter, Text = $"读取值：", Size = new Size(Width, Height), Location = new Point(Convert.ToInt16(xOffset - 1.5 * Margin), yOffset + Margin / 2) };
            num.Controls.Add(labelda);
            Label labeldaWrite = new Label { TextAlign = ContentAlignment.MiddleCenter, Text = $"写入值(V)：", Size = new Size(Width, Height), Location = new Point(Convert.ToInt16(xOffset - 1.5 * Margin), yOffset + Margin) };
            num.Controls.Add(labeldaWrite);
            for (int i = 0; i < ToolsForm.dataControl[IPName].DANum; i++)
            {
                Label daName = new Label { TextAlign = ContentAlignment.MiddleCenter, Text = $"DA{i}", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset) };
                Label daNum = new Label { Name = $"DARead{i}", TextAlign = ContentAlignment.MiddleCenter, Text = "0.00", Size = new Size(Width, Height), Location = new Point(xOffset, yOffset + Margin / 2) };
                NumericUpDown daWrite = new NumericUpDown { Name = $"DAWrite{i}", Value = 0, DecimalPlaces = 2, Maximum = 10, Size = new Size(Convert.ToInt16(Width * 0.8), Height), Location = new Point(xOffset, yOffset + Margin) };
                xOffset += Margin;
                num.Controls.Add(daName);
                num.Controls.Add(daNum);
                num.Controls.Add(daWrite);
            }
            //读取
            yOffset += 2 * Margin;
            xOffset = 3 * Margin;
            //按钮
            Button btn_write = new Button { Text = "写入", Size = new Size(Width, Height), Location = new Point(xOffset + Margin, yOffset) };
            btn_write.Click += (sender, e) =>
            {
                for (int i = 0; i < ToolsForm.dataControl[IPName].DANum; i++)
                {
                    float a = 4095 / 10;
                    Control dawrite = num.Controls.Find($"DAWrite{i}", true).FirstOrDefault();
                    if (dawrite != null && dawrite is NumericUpDown)
                    {
                        PMC_SetDA(IPName.handle, i, Convert.ToSingle(dawrite.Text));
                    }
                }
            };
            num.Controls.Add(btn_write);
        }
    }
}
